<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\UserModel;
use Overtrue\Wechat\Auth;
use Validator;
use Session;
class UserController extends Controller
{
    //前端逻辑
    public function login(Request $req)
    {
        if ($req->session()->get('user')) {
            return redirect('/home/show');
        }
        $auth = new Auth(env('WX_ID'), env('WX_SEC'));
        $user = $auth->authorize();
        $req->session()->put('user', $user->all());
        return back();
    }


    public function logout(Request $req)
    {
        $req->session()->forget('user');
        echo 'logout ok';
    }


    //后端展示
    public function index()
    {
        $data['data'] = UserModel::paginate(10);
        $data['type'] = 3;
        return view('user.index', compact('data'));
    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $res = UserModel::where(['id' => $id])->first();
        if (!empty($res)) {
            UserModel::where(['id' => $id])->delete();
            return response()->json(['status' => 200, 'msg' => '删除成功']);
        }
        return response()->json(['status' => 500, 'msg' => '删除失败']);
    }

    public function test()
    {
        $res = UserModel::where(['id' => 1])->first();
        dd($res);
    }


    public function edit(Request $request,$id){

        if($request->isMethod('get')){
            $data=UserModel::where('id',$id)->first();
            return view('user.edit',compact('data'));
        }else{
            $data = $request->except(['_token','uploadfile']);
            $validator = Validator::make($data, [
                'name'     => 'required|string',
                'mobile'     => 'required|string',
                'school' => 'required|string',
                'role' => 'required|string',
                'college' => 'required|string',
                'student_num' => 'required|string',
                'dormitory' => 'required|string',
            ]);
            if ($validator->fails()) {
                return redirect('/admin/article/add')
                    ->withErrors($validator)
                    ->withInput($data);
            }
            $data=UserModel::where('id',$id)->update($data);
            return redirect('/admin/user/index');
        }
    }




}
